/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "tw_nfc_adapt.h"

void TWNfcI2cInit(void)
{
    unsigned int ret = 0;

    IoTGpioInit(IOT_IO_NAME_GPIO_13);
    IoTGpioInit(IOT_IO_NAME_GPIO_14);

    IoTIoSetPull(IOT_IO_NAME_GPIO_13, IOT_IO_PULL_UP);
    IoTIoSetPull(IOT_IO_NAME_GPIO_14, IOT_IO_PULL_UP);

    IoTIoSetFunc(IOT_IO_NAME_GPIO_13, IOT_IO_FUNC_GPIO_13_I2C0_SDA);
    IoTIoSetFunc(IOT_IO_NAME_GPIO_14, IOT_IO_FUNC_GPIO_14_I2C0_SCL);

    ret = IoTI2cInit(NFC_I2C_INDEX, 400000);
    if (ret != IOT_SUCCESS)
    {
        printf("I2c Init failed 0, ret = %u\r\n", ret);
    }

    // csn引脚
    IoTGpioInit(IOT_IO_NAME_GPIO_9);
    IoTIoSetFunc(IOT_IO_NAME_GPIO_9, 0);
    IoTIoSetPull(IOT_IO_NAME_GPIO_9, IOT_IO_PULL_UP);
    IoTGpioSetDir(IOT_IO_NAME_GPIO_9, IOT_GPIO_DIR_OUT);
    IoTGpioSetOutputVal(IOT_IO_NAME_GPIO_9, 0);
}

int NfcI2cWrite(const unsigned char *data, unsigned int dataLen)
{
    osDelay(1);
    unsigned int ret = IoTI2cWrite(NFC_I2C_INDEX, NFC_WRITE_ADDR, data, dataLen);
    if (ret != IOT_SUCCESS)
    {
        osDelay(1);
        ret = IoTI2cWrite(NFC_I2C_INDEX, NFC_WRITE_ADDR, data, dataLen);
        if (ret != IOT_SUCCESS)
        {
            printf("IoTI2cWrite fail 1, ret = %u\r\n", ret);
            return IOT_FAILURE;
        }
    }

    return IOT_SUCCESS;
}

int NfcI2cRead(const unsigned char *data, unsigned int dataLen)
{
    unsigned int ret = IoTI2cRead(NFC_I2C_INDEX, NFC_READ_ADDR, data, dataLen);
    if (ret != IOT_SUCCESS)
    {
        osDelay(1);
        ret = IoTI2cRead(NFC_I2C_INDEX, NFC_READ_ADDR, data, dataLen);
        if (ret != IOT_SUCCESS)
        {
            printf("IoTI2cRead fail 5, ret = %u\r\n", ret);
            return IOT_FAILURE;
        }
    }
    return IOT_SUCCESS;
}